/**
 * markdown escaped characters
 */
const markdownEncodeReg = /[\\`*{}[\]#+!|]/g
const markdownDecodeReg = /\\([\\`*{}[\]#+!|])/g

export class TextHelper {
	public static splitToLines(str: string): string[] {
		return str.split(/\r\n|\n/)
	}

	public static width(str: string): number {
		if (!str || str.length === 0) {
			return 0
		}
		let width = 0
		for (let i = 0; i < str.length; i += 1) {
			width += str.charCodeAt(i) > 255 ? 2 : 1
		}

		return width
	}

	public static padEnd(str: string, maxLen: number, fileString: string = ' '): string {
		const textWidth = TextHelper.width(str)
		if (maxLen - textWidth > 0) {
			return `${str}${''.padEnd(maxLen - textWidth, fileString)}`
		}

		return str
	}

	/**
	 * encode a text to a markdown text
	 * - end of line
	 * @param str text
	 * @returns the markdown text
	 */
	public static encodeMarkdown(str: string): string {
		if (!str) {
			return ''
		}

		// escaped
		let escaped = str.replace(markdownEncodeReg, TextHelper.encodeReplacer)
		// escaped = escaped.replace(/&/g, '&amp;')
		// escaped = escaped.replace(/</g, '&lt;')
		escaped = escaped.replace(/(\r\n|\r|\n)/g, '<br>')
		return escaped
	}

	/**
	 * decode a text to a markdown text
	 * - end of line
	 * @param str the markdown text
	 * @returns the decoded text
	 */
	public static decodeMarkdown(str: string): string {
		if (!str) {
			return ''
		}

		// escaped
		let escaped: string = str.replace(/<br>/g, '\n')
		// escaped = escaped.replace(/&lt;/g, '<')
		// escaped = escaped.replace(/&amp;/g, '&')
		escaped = escaped.replace(markdownDecodeReg, TextHelper.decodeReplacer)
		return escaped
	}

	private static encodeReplacer(match: string): string {
		return `\\${match}`
	}

	private static decodeReplacer(_match: string, p1: string) {
		return p1
	}
}
